<template>
  <div>
    <!-- 模块选择 -->
    <div class="module-selector">
      <el-radio-group v-model="activeModule" @change="handleModuleChange">
        <el-radio-button label="activity">学生评价管理</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
        </el-form-item>
        <el-form-item label="发布人">
          <el-input
              v-model="searchForm.publisher"
              placeholder="请输入发布人"
              clearable
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="年级">
          <el-select
              v-model="searchForm.grade"
              placeholder="请选择年级"
              clearable
              style="width: 120px"
          >
            <el-option label="一年级" value="1" />
            <el-option label="二年级" value="2" />
            <el-option label="三年级" value="3" />
            <el-option label="四年级" value="4" />
            <el-option label="五年级" value="5" />
            <el-option label="六年级" value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-select
              v-model="searchForm.classNum"
              placeholder="请选择班级"
              clearable
              style="width: 120px"
          >
            <el-option label="1班" value="1" />
            <el-option label="2班" value="2" />
            <el-option label="3班" value="3" />
            <el-option label="4班" value="4" />
            <el-option label="5班" value="5" />
          </el-select>
        </el-form-item>

        <el-form-item label="学生姓名">
          <el-input v-model="searchForm.studentName" placeholder="请输入学生姓名" clearable />
        </el-form-item>

        <el-form-item label="发布时间">
          <el-date-picker
              v-model="searchForm.createTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="container">
      <!-- 操作按钮区域 -->
      <div class="toolbar-container">
        <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          批量删除
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" width="55" align="center" />

        <!--        <el-table-column prop="id" label="ID调试" width="100" align="center" />-->
        <el-table-column prop="publisher" label="发布人" width="120" align="center" />
        <el-table-column prop="studentName" label="学生姓名" width="120" align="center" />
        <el-table-column label="年级" width="100" align="center">
          <template #default="{ row }">
            {{ row.grade ? `${row.grade}年级` : '已毕业' }}
            <!--            {{ row.grade === null ? '已毕业' : `${row.grade}年级` }}-->

          </template>
        </el-table-column>

        <el-table-column label="班级" width="100" align="center">
          <template #default="{ row }">
            {{ row.classNum ? `${row.classNum}班` : '-' }}
            <!--            {{ row.classNum ? `${row.classNum}班` : '-' }}-->
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="200" align="center" />
        <el-table-column prop="content" label="评价内容" width="300" align="center">
          <template #default="{ row }">
            <el-popover
                placement="top-start"
                :width="400"
                trigger="hover"
                :content="row.content"
            >
              <template #reference>
                <div class="content-preview">
                  {{ row.content.length > 20 ? row.content.substring(0, 20) + '...' : row.content }}
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="pubTime" label="发布时间" width="180" align="center" />
        <el-table-column prop="updateTime" label="修改时间" width="180" align="center" />
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="warning" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="page.index"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="changePage"
          @size-change="handleSizeChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        :title="`${isEdit ? '编辑' : '新增'}评价`"
        v-model="visible"
        width="900px"
        destroy-on-close
        :close-on-click-modal="false"
        @close="closeDialog"
    >
      <el-form :model="rowData" label-width="100px" ref="formRef">
        <!--        学生选择器-->
        <el-form-item label="学生姓名" prop="studentId" required :rules="[{ required: true, message: '请选择学生', trigger: 'change' }]"
                      v-if="!isEdit"
        >
          <el-select
              v-model="rowData.studentId"
              placeholder="请输入或选择学生"
              style="width: 100%"
              filterable

              @change="handleStudentChange"
          >
            <el-option
                v-for="student in studentOptions"
                :key="student.value"
                :label="student.label"
                :value="student.value"
            />
          </el-select>




          <!--          老师选择器-->
        </el-form-item>
        <el-form-item label="发布人" prop="publisher" required :rules="[{ required: true, message: '请输入发布人', trigger: 'blur' }]"
                      v-if="!isEdit"
        >

          <el-select
              v-model="rowData.pubId"
              placeholder="请选择发布人"
              style="width: 100%"
              filterable
              @change="handleTeacherChange"
          >
            <el-option
                v-for="teacher in teacherOptions"
                :key="teacher.value"
                :label="teacher.label"
                :value="teacher.value"
            />
          </el-select>



          <!--                  <el-select-->
          <!--                            v-model="rowData.pubId"-->
          <!--                             @change="handleTeacherChange"-->
          <!--                             placeholder="请选择发布人"-->
          <!--                             style="width: 100%">-->
          <!--                    <el-option-->
          <!--                        v-for="teacher in teacherOptions"-->
          <!--                        :key="teacher.id"-->
          <!--                        :label="teacher.name"-->
          <!--                        :value="teacher.id"-->
          <!--                    />-->
          <!--                  </el-select>-->
        </el-form-item>

        <el-form-item label="年级" prop="grade" required v-if="!isEdit"
                      :rules="[{ required: true, message: '请选择年级', trigger: 'change' }]">
          <el-select v-model="rowData.grade" placeholder="请选择年级" style="width: 100%">
            <el-option label="一年级" value="1" />
            <el-option label="二年级" value="2" />
            <el-option label="三年级" value="3" />
            <el-option label="四年级" value="4" />
            <el-option label="五年级" value="5" />
            <el-option label="六年级" value="6" />
          </el-select>
        </el-form-item>

        <el-form-item label="班级" prop="class" required  v-if="!isEdit" :rules="[{ required: true, message: '请选择班级', trigger: 'change' }]">
          <el-select v-model="rowData.class" placeholder="请选择班级" style="width: 100%">
            <el-option label="1班" value="1" />
            <el-option label="2班" value="2" />
            <el-option label="3班" value="3" />
            <el-option label="4班" value="4" />
            <el-option label="5班" value="5" />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title" required :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
          <el-input v-model="rowData.title" />
        </el-form-item>

        <el-form-item label="评价内容" prop="content" required :rules="[{ required: true, message: '请输入评价内容', trigger: 'blur' }]">
          <el-input
              v-model="rowData.content"
              type="textarea"
              :rows="20"
              placeholder="请输入评价内容"
              style="height: 400px;"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog title="评价详情" v-model="detailVisible" width="900px" destroy-on-close>
      <div class="activity-detail">
        <h2 class="activity-title">{{ detailData.title }}</h2>
        <div class="activity-meta">
<!--          <span>发布人: {{ detailData.publisher|| '-' }}</span>-->
          <span>学生: {{ detailData.studentName }}</span>
          <span>年级: {{ detailData.grade }}年级</span>
          <span>班级: {{ detailData.classNum }}班</span>
          <span>发布时间: {{ detailData.pubTime }}</span>
        </div>
        <div class="activity-content">
          <pre>{{ detailData.content }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, computed, onMounted} from 'vue';
import {dayjs, ElMessage, ElMessageBox, type FormInstance} from 'element-plus';
import { CirclePlusFilled, Delete } from '@element-plus/icons-vue';
import {
  getCommentList,
  getCommentDetail,
  deleteComment,
  batchDeleteComment,
  updateComment,
  createComment,
  getTeacherList,
  getStudentList
} from "@/api/comment";
onMounted(() => {
  fetchData();
  fetchTeachers();//加载老师列表
  fetchStudents();// 加载学生列表
});


// 学生和老师选项
const studentOptions = ref<{label: string, value: number}[]>([]);
const teacherOptions = ref<{label: string, value: number}[]>([]);

// 加载学生列表
const fetchStudents = async () => {
  try {
    const res = await getStudentList();
    if (res.data && Array.isArray(res.data)) {
      studentOptions.value = res.data.map(student => ({
        label: student.realName || student.name || '未知学生',
        value: student.id
      }));
    } else {
      throw new Error('学生列表数据格式不正确');
    }
  } catch (err) {
    console.error('获取学生列表失败', err);
    ElMessage.error('获取学生列表失败，请刷新重试');
    studentOptions.value = []; // 清空选项避免错误
  }
};


// 加载老师列表
const fetchTeachers = async () => {
  try {
    const res = await getTeacherList();
    if (res.data && Array.isArray(res.data)) {
      teacherOptions.value = res.data.map(teacher => ({
        label: teacher.realName || teacher.name || '未知老师',
        value: teacher.id
      }));
    } else {
      throw new Error('老师列表数据格式不正确');
    }
  } catch (err) {
    console.error('获取老师列表失败', err);
    ElMessage.error('获取老师列表失败，请刷新重试');
    teacherOptions.value = []; // 清空选项避免错误
  }
};


// 学生搜索相关
const studentLoading = ref(false);
// 搜索学生方法
const searchStudents = async (query: string) => {
  if (query) {
    studentLoading.value = true;
    try {
      const res = await getStudentList({ name: query });
      studentOptions.value = res.data.map(student => ({
        label: student.realName,
        value: student.id
      }));
    } catch (err) {
      console.error('搜索学生失败', err);
    } finally {
      studentLoading.value = false;
    }
  }
};
// 学生选择变化处理
const handleStudentChange = (studentId: number) => {
  const selected = studentOptions.value.find(s => s.value === studentId);
  if (selected) {
    rowData.value.studentName = selected.label;
    rowData.value.studentId = studentId;
    // rowData.value.pubId = studentId;// 设置实际ID值
  }
};
// 老师选择变化处理
const handleTeacherChange = (teacherId: number) => {
  const selected = teacherOptions.value.find(t => t.value === teacherId);
  if (selected) {
    rowData.value.publisher = selected.label;// 设置显示名称
    rowData.value.pubId = teacherId;// 设置实际ID值
  }
};

// 当前激活的模块
const activeModule = ref<'activity'>('activity');
const formRef = ref<FormInstance>();
const total = ref(0);

// 使用强类型定义
const tableData = ref<any[]>([]);
const selectedIds = ref<number[]>([]);
const rowData = ref<any>({
  id: null,
  studentId: null,
  studentName: '',
  publisher: '',
  pubId: null,
  type: '评价',
  grade: null,
  classNum:null,
  // class: null,
  title: '',
  content: '',
  pubTime: '',
  updateTime: ''
});


// 搜索表单
const searchForm = reactive({
  title: '',
  publisher: '',
  studentName:'',
  grade: null, // 使用grade而不是gradeYear
  classNum: null,
  createTime: [],
  type:'评价'
});


// 分页相关
const page = reactive({
  index: 1,
  size: 10,
  total: 0
});

const changePage = (val: number) => {
  page.index = val;
  fetchData();
};

const handleSizeChange = (val: number) => {
  page.size = val;
  fetchData();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id);
};

// 搜索
const handleSearch = () => {
  page.index = 1;
  fetchData();
};

//重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    title: '',
    publisher: '',
    grade: '',
    studentName:'',
    // gradeYear:'',
    classNum:'',
    // class: '',
    createTime: []
  });
  handleSearch();
};

// 弹窗相关
const visible = ref(false);
const detailVisible = ref(false);
const isEdit = ref(false);
const detailData = ref<any>({});

// 模块切换处理
const handleModuleChange = () => {
  resetSearch();
  changePage(1);
};

// 初始化新增数据
const initNewData = () => {
  return {
    id: null,
    studentId: null,
    studentName: '',
    publisher: '',
    pubId:null,
    type:'评价',
    grade:null,
    // grade: '',
    classNum:null,
    // classNum:'',
    title: '',
    content: '',
    pubTime: '',
    updateTime: ''
  };
};

const fetchData = async () => {
  try {
    const params  = {
      title: searchForm.title,
      publisher: searchForm.publisher,
      studentName: searchForm.studentName,
      grade: searchForm.grade,
      classNum: searchForm.classNum, // 注意 class 是关键字，建议后端用 classNum 或 className
      startTime: searchForm.createTime?.[0],
      endTime: searchForm.createTime?.[1],
      page: page.index,
      pageSize: page.size,
      type:'评价'
    };
    const res = await getCommentList(params);
    tableData.value = res.data.list ;
    // tableData.value = res.data.list;
    console.log(tableData.value)
    page.total = res.data.total;
    // total.value = res.data.total;
  } catch (err) {
    ElMessage.error('获取评价数据失败');
  }
};


// 查看按钮点击
const handleView = async (row: any) => {
  try {

    const res = await getCommentDetail(row.id);
    detailData.value = res.data;
    detailVisible.value = true;
  } catch (err) {
    ElMessage.error('获取活动详情失败');
  }
};

// 添加时间格式化函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-';
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss');
};

//新增
const handleAdd = () => {
  isEdit.value = false;
  rowData.value = initNewData();
  visible.value = true;
};

// 编辑按钮点击
const handleEdit = (row: any) => {
  isEdit.value = true;
  rowData.value = {
    ...initNewData(),
    ...row,
    // 确保编辑时正确设置发布人信息
    publisher: row.publisher || teacherOptions.value.find(t => t.value === row.pubId)?.label || '',
    pubId: row.pubId || null
  };
  visible.value = true;
};

// 提交
const handleConfirm = async () => {

  try {
    // 1. 先进行表单验证
    await formRef.value?.validate();

    // 2. 新增时检查必填项
    if (!isEdit.value && !rowData.value.studentId) {
      ElMessage.error("必须选择学生");
      return;
    }
    if (!isEdit.value &&!rowData.value.pubId) {
      ElMessage.error("必须选择发布人");
      return;
    }
    // 3. 构建提交数据
    const submitData = {
      id: rowData.value.id || null, // 新增时为null
      studentId: Number(rowData.value.studentId),
      studentName: rowData.value.studentName,
      pubId: Number(rowData.value.pubId),
      publisher: rowData.value.publisher,
      title: rowData.value.title,
      content: rowData.value.content,
      type: '评价',
      grade: rowData.value.grade ? Number(rowData.value.grade) : null,
      classNum: rowData.value.classNum ? Number(rowData.value.classNum) : null,
      // 时间处理（根据实际API需求调整）
      pubTime:'',
      updateTime: ''
    };

    // 调试：打印提交数据
    console.log('提交数据:', submitData);

    // 4. 根据编辑/新增状态调用不同API
    if (isEdit.value) {
      await updateComment(submitData);
      ElMessage.success('编辑成功');
    } else {
      await createComment(submitData);
      ElMessage.success('新增成功');
    }

    // 5. 关闭弹窗并刷新数据
    visible.value = false;
    fetchData();
  } catch (error) {
    // 6. 错误处理（关键修改点）
    if (error.response) {
      console.error('API错误:', {
        request: error.config?.data,
        response: error.response.data
      });
      ElMessage.error(`操作失败: ${error.response.data?.message || '服务器错误'}`);
    } else if (error instanceof Error) {
      console.error('验证错误:', error.message);
      // Element UI会自动显示验证错误，这里不需要重复提示
    } else {
      console.error('未知错误:', error);
      ElMessage.error('操作失败，请重试');
    }
  }
};

const closeDialog = () => {
  visible.value = false;
};

//删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该评价数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteComment(row.id);
    ElMessage.success('删除成功');
    fetchData();
  } catch (err) {
    console.error(err);
  }
};

//批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  try {
    await ElMessageBox.confirm('确定要删除选中的评价数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await batchDeleteComment(selectedIds.value);
    ElMessage.success('批量删除成功');
    fetchData();
    selectedIds.value = [];
  } catch (err) {
    console.error(err);
  }
};
</script>

<style scoped>
.module-selector {
  margin-bottom: 20px;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-container {
  padding: 20px;
  background: #fff;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.container {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  position: relative;
}

.toolbar-container {
  margin-bottom: 20px;
  text-align: right;
}

.el-table {
  margin-bottom: 15px;
  width: 100%;
}

.el-pagination {
  justify-content: flex-end;
  margin-top: 15px;
}

/* 确保表格列宽总和与表格宽度匹配 */
:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

.content-preview {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.activity-detail {
  padding: 20px;
}

.activity-title {
  font-size: 24px;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.activity-meta {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.activity-meta span {
  margin-right: 20px;
  margin-bottom: 10px;
}

.activity-content {
  font-size: 16px;
  line-height: 1.8;
  white-space: pre-wrap;
  background: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
  font-family: inherit;
  max-height: 500px;
  overflow-y: auto;
}

.activity-content pre {
  white-space: pre-wrap;
  font-family: inherit;
  margin: 0;
}

/* 调整对话框内容区域样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

/* 调整文本输入框样式 */
:deep(.el-textarea__inner) {
  min-height: 400px !important;
  font-family: monospace;
  white-space: pre;
}
</style>
